package com.wskj.common.utils.qrcode;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtil {

    /**
     * url转变为 MultipartFile对象
     * @param url
     * @param fileName
     * @return
     * @throws Exception
     */
    public static MultipartFile createFileItem(String url, String fileName) throws Exception{
        FileItem item = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setReadTimeout(30000);
            conn.setConnectTimeout(30000);
            //设置应用程序要从网络连接读取数据
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();
                FileItemFactory factory = new DiskFileItemFactory(16, null);
                String textFieldName = "qrCodeFile";
                item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName);
                OutputStream os = item.getOutputStream();
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                is.close();
            }
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败", e);
        }
        return new CommonsMultipartFile(item);
    }

    /**
     * MultipartFile 类型转换为file类型
     * @param multipartFile
     * @return
     */
    public static  File transferToFile(MultipartFile multipartFile) {
       // 选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file=File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * file类型转换为MultipartFile类型
     * @param file
     * @return
     */
    public static MultipartFile transferToMultipartFile(File file){
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(file.getName(), "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        MultipartFile multipartFile = new CommonsMultipartFile(item);
        return multipartFile;
    }

    /**
     * BufferedImage 类型转换为MultipartFile类型
     * @param image
     * @return
     */
    public static MultipartFile transferImageToMultipartFile(BufferedImage image){
        MultipartFile multipartFile = null;
        try {
            //读取图片转换为 BufferedImage
            //调整图片大小后的BufferedImage。resizeImage方法是调整图片大小的可参考文章开头我上一篇文章
            // BufferedImage newImage = ImageUtils.resizeImage(image, 200, 200);
            //将newImage写入字节数组输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos );
            //转换为MultipartFile
            multipartFile = new MockMultipartFile("pic1.jpg", baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }
}
